package com.scrcu.core.batch.biz;

import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.scrcu.core.batch.dao.SqlSessionDao;
import com.scrcu.core.batch.entity.BatchInfo;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class BatchInfoBizImpl extends SqlSessionDao implements BatchInfoBiz {

    private final String namespace = "com.scrcu.core.batch.BatchInfo.";

    public BatchInfoBizImpl(SqlSession dao) {
        super(dao);
    }

    @Override
    @Transactional(readOnly = true)
    public PagedResult<BatchInfo> list(String catalog, String key, String orderBy, int pageNo, int pageSize) {
        Map param = new HashMap<>();
        param.put("catalog", catalog);
        param.put("key", "%".concat(key).concat("%"));//模糊查询在这里拼接，防止sql注入
        param.put("start", pageNo * pageSize);
        param.put("pageSize", pageSize);
        param.put("orderBy", orderBy);
        int total = dao.selectOne(namespace.concat("selectCountBySelective"),param);
        List<BatchInfo> lt = dao.selectList(namespace.concat("selectBySelective"),param);
        return new PagedResult<BatchInfo>(total, lt, pageNo, pageSize);
    }

    @Transactional(readOnly = true)
    public BatchInfo find(String code) {
        return dao.selectOne(namespace.concat("selectByCode"), code);
    }

    @Override
    @Transactional(readOnly = true)
    public BatchInfo get(String id) {
        return dao.selectOne(namespace.concat("selectById"), id);
    }

    @Override
    @Transactional
    public String save(BatchInfo o) {
        if (Util.strIsEmpty(o.getId())) {
            dao.insert(namespace.concat("insertSelective"), o);
        } else {
            dao.update(namespace.concat("updateSelective"), o);
        }
        return o.getId();
    }

    @Override
    @Transactional
    public void delete(String id) {
        // 删除执行记录的相关事件
        dao.delete("com.scrcu.core.batch.BatchEvent.deleteByInfoId",id);
        // 删除执行记录
        dao.delete("com.scrcu.core.batch.BatchExecution.deleteByInfoId",id);
        // 删除批量定义
        dao.delete(namespace.concat("deleteById"), id);
    }

    @Override
    @Transactional
    public boolean enable(String id) {
        return dao.update(namespace.concat("enableRunBatch"),id) == 1;
    }

    @Override
    @Transactional
    public boolean disable(String id) {
        return dao.update(namespace.concat("disableRunBatch"),id) == 1;
    }
}